package com.rayboo.example.collections.iterator;

import java.util.*;

/**
 * Iterator 示例
 *
 * @author ray
 * @since 2019/07/25
 *
 * <p>Iterator用于迭代（循环）各种集合类，如HashMap，ArrayList，LinkedList等。
 * Iterator取代了Enumeration，它用于迭代传统的类，如Vector。
 *
 * <p>https://beginnersbook.com/2014/06/java-iterator-with-examples/
 */
public class IteratorExample {

    public static void main(String a[]) {
        System.out.println("============ Loop ArrayList ==========");

        ArrayList<String> arrayList = new ArrayList<String>();
        arrayList.add("Chaitanya");
        arrayList.add("Steve");
        arrayList.add("Jack");

        Iterator<String> it = arrayList.iterator();

        while (it.hasNext()) {
            String obj = it.next();
            System.out.println(obj);
        }

        System.out.println("\n============ Loop HashMap ==========");

        HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
        //Adding elements to HashMap
        hashMap.put(11, "AB");
        hashMap.put(2, "CD");
        hashMap.put(33, "EF");
        hashMap.put(9, "GH");
        hashMap.put(3, "IJ");

        //FOR LOOP
        System.out.println("For Loop:");
        for (Map.Entry me : hashMap.entrySet()) {
            System.out.println("Key: " + me.getKey() + " & Value: " + me.getValue());
        }

        //WHILE LOOP & ITERATOR
        System.out.println("While Loop:");
        Iterator iterator = hashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry me2 = (Map.Entry) iterator.next();
            System.out.println("Key: " + me2.getKey() + " & Value: " + me2.getValue());
        }

        System.out.println("\n============ Loop LinkedList ==========");

        /*LinkedList declaration*/
        LinkedList<String> linkedList = new LinkedList<String>();
        linkedList.add("Apple");
        linkedList.add("Orange");
        linkedList.add("Mango");

        /*Using For loop*/
        System.out.println("**For Loop**");
        for (int num = 0; num < linkedList.size(); num++) {
            System.out.println(linkedList.get(num));
        }

        /*Using Advanced for loop*/
        System.out.println("**Advanced For loop**");
        for (String str : linkedList) {
            System.out.println(str);
        }

        /*Using Iterator*/
        System.out.println("**Iterator**");
        Iterator i = linkedList.iterator();
        while (i.hasNext()) {
            System.out.println(i.next());
        }

        /*Using While Loop*/
        System.out.println("**While Loop**");
        int num = 0;
        while (linkedList.size() > num) {
            System.out.println(linkedList.get(num));
            num++;
        }
    }
}
